/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.OneCommerceProject.controllers;

import com.OneCommerceProject.beans.CommandefourFacade;
import com.OneCommerceProject.beans.ItemFourFacade;
import com.OneCommerceProject.beans.UtilisateurFacade;
import com.OneCommerceProject.controllers.util.JsfUtil;
import com.OneCommerceProject.entities.*;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

/**
 *
 * @author Aymen
 */
@ManagedBean
@SessionScoped
public class UtilLogin implements Serializable {

    @EJB
    private com.OneCommerceProject.beans.UtilisateurFacade utilFacade;
    @EJB
    private com.OneCommerceProject.beans.ItemFacade itemFacade;
    @EJB
    private com.OneCommerceProject.beans.CommandeclientFacade commandeclientFacade;
    @EJB
    private com.OneCommerceProject.beans.UtilisateurFacade utilisateurFacade;    
    @EJB
    private CommandefourFacade commandefourFacade;
    @EJB
    private ItemFourFacade itemFourFacade;
    private BigInteger quantite;
    private Utilisateur util = new Utilisateur();
    private String login;
    private String password;
    private boolean connected = false;
    private boolean edit = false;
    private boolean admin = false;    
    private List<Commandeclient> itemCommanded = new ArrayList<Commandeclient>();
    private Commandeclient selectedCommandeclient = null;
    
    public String getRang() {
        List<Utilisateur> listUtil = getUtilisateurFacade().findClientFidele();        
        return String.valueOf(listUtil.indexOf(util) + 1);
    }      
    
    public UtilisateurFacade getUtilisateurFacade() {
        return utilisateurFacade;
    }
    
    public Commandeclient getSelectedCommandeclient() {
        return selectedCommandeclient;
    }

    public void setSelectedCommandeclient(Commandeclient selectedCommandeclient) {
        this.selectedCommandeclient = selectedCommandeclient;
    }
    
    public void setAdmin(boolean admin) {        
        this.admin = admin;
    }
    
    public boolean isAdmin() {   
        if (!isConnected()) {
            return false;
        }
        return admin;
    }

    public boolean isConnected() {
        return connected;
    }

    public BigInteger getQuantite() {
        return quantite;
    }

    public void setQuantite(BigInteger quantite) {
        this.quantite = quantite;
    }

    public Utilisateur getUtil() {
        return util;
    }

    public void setUtil(Utilisateur util) {
        this.util = util;
    }

    public void setConnected(boolean connected) {
        this.connected = connected;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void connect() {
        util = utilFacade.findByLogin(login);
        if (util != null) {
            if ((password.equals(util.getPassword()))) {
                if (!util.getTypeclient().equals("Admin")) {                    
                    this.setConnected(true);
                    util.setConnected(true);
                    List<Commandeclient> tmp = commandeclientFacade.findByUtil(util);
                    Date systemDate = new Date();
                    for (Commandeclient c : tmp) {
                        if (c.getStatutreser().equals("Active")) {
                            if ((systemDate.getTime() - c.getDateReser().getTime()) >= 3 * 24 * 3600 * 1000) {
                                c.setStatutreser("nonActive");
                                commandeclientFacade.edit(c);
                            };
                            itemCommanded.add(c);
                        }
                    }
                    utilFacade.edit(util);                    
                } else {
                    this.setConnected(true);
                    setAdmin(true);
                    util.setConnected(true);
                    List<Commandeclient> tmp = commandeclientFacade.findByStatutReserList("Active");
                    Date systemDate = new Date();
                    for (Commandeclient c : tmp) {
                        if ((systemDate.getTime() - c.getDateReser().getTime()) >= 3 * 24 * 3600 * 1000) {
                            c.setStatutreser("nonActive");
                            commandeclientFacade.edit(c);
                        };
                    }
                    utilFacade.edit(util);                    
                }
            } else {
                String msg = "Login / Password Incorrect";
                JsfUtil.addErrorMessage(msg);                
            }
        } else {
            String msg = "Login / Password Incorrect";
            JsfUtil.addErrorMessage(msg);            
        }
    }

    public String disconnect() {
        setConnected(false);
        util.setConnected(false);
        admin = false;
        utilFacade.edit(util);
        util = new Utilisateur();
        login = null;
        password = null;
        selectedCommandeclient = null;
        itemCommanded.clear();
        return "/user/public?faces-redirect=true";
    }
   public void delete() {
        try {
            selectedCommandeclient.setStatutreser("nonActive");
            commandeclientFacade.edit(selectedCommandeclient);
            itemCommanded.remove(selectedCommandeclient);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CommandeclientDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }
    public void commander() {
        if (quantite != null && !quantite.toString().equals("0")) {
            ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
            String itemId = externalContext.getRequestParameterMap().get("item");
            Commandeclient commandeClient = new Commandeclient();
            Item item = itemFacade.find(new BigDecimal(itemId));
            commandeClient.setDateReser(new Date());
            commandeClient.setIditem(item);
            commandeClient.setStatutreser("Active");
            commandeClient.setEtatcomm("nonActive");
            commandeClient.setQuantite(quantite);
            commandeClient.setIdutil(util);
            commandeclientFacade.create(commandeClient);
            quantite = null;
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CommandeclientCreated"));
            itemCommanded.add(commandeClient);
        } else {
            JsfUtil.addErrorMessage("Entrer une valeur !!!");
        }
    }


    public void confirmChangesAndReservation() {
        util.setTypeclient("Prospect");
        utilFacade.edit(util);
        commander();
    }

    public void confirmChangesAndCommand() {
        util.setTypeclient("Client");
        utilFacade.edit(util);
        confirmCommand();
    }

    public void confirmCommand() {
        Item item = selectedCommandeclient.getIditem();
        int i = Integer.valueOf(selectedCommandeclient.getIditem().getQuantiteitem().toString()) - Integer.valueOf(selectedCommandeclient.getQuantite().toString());
        if (i >= 0) {
            item.setQuantiteitem(new BigInteger(String.valueOf(i)));
            item.setNbreVente(item.getNbreVente().add(selectedCommandeclient.getQuantite()));
            itemFacade.edit(item);
            util.setNbreachat(util.getNbreachat().add(selectedCommandeclient.getQuantite()));
            utilFacade.edit(util);
            JsfUtil.addSuccessMessage("Your commande has been successfully created");
            selectedCommandeclient.setStatutreser("nonActive");
            selectedCommandeclient.setEtatcomm("confirmed");
            itemCommanded.remove(selectedCommandeclient);
            commandeclientFacade.edit(selectedCommandeclient);            
            if (Integer.valueOf(selectedCommandeclient.getIditem().getSeuilmin().toString()) >= i) {
                Commandefour commandefour = new Commandefour();
                commandefour.setDatecomfour(new Date());
                commandefour.setIditem(selectedCommandeclient.getIditem());
                List<ItemFour> itemFours = itemFourFacade.findAll();
                for (ItemFour ii : itemFours) {
                    if (ii.getItem().equals(selectedCommandeclient.getIditem()) && ii.getLeader()) {
                        commandefour.setIdfour(ii.getFournisseur());
                        break;
                    }
                }
                commandefourFacade.create(commandefour);
            }
        } else {
            JsfUtil.addErrorMessage("Sorry we are out of Item ;)");
        }
    }

    public String update() {
        if (!edit) {
            edit = true;
        } else {
            JsfUtil.addSuccessMessage("Edition a été faite avec succes !!");
            utilFacade.edit(util);
            edit = false;
        }
        return "/user/editDetails.xhtml?faces-redirect=true";
    }

    public boolean isEdit() {
        return edit;
    }

    public List<Commandeclient> getItemCommanded() {
        return itemCommanded;
    }
}
